import { getMenuList } from '@/api/login'
import { resetRouter } from '@/router'

/**
 * 
 * @description 重写trim方法，去除字符串首尾指定字符
 * @param {String} char 删除的字符
 * @param {String} type 左右位置，值为left、right，不传则是首尾两端
 */
String.prototype.trim = function (char, type) {
  if (char) {
      if (type == 'left') {
          return this.replace(new RegExp('^\\'+char+'+', 'g'), '')
      } else if (type == 'right') {
          return this.replace(new RegExp('\\'+char+'+$', 'g'), '')
      }
      return this.replace(new RegExp('^\\'+char+'+|\\'+char+'+$', 'g'), '')
  }
  return this.replace(/^\s+|\s+$/g, '')
}

const formatList = (menu) => {
  menu.map(item => {
    if (!item.resourceUrl && item.child.length) {
      const childUrl = item.child[0].resourceUrl.trim('/').split('/')
      item.resourceUrl = childUrl[0]
      let childMenu = []
      item.child.map(itemSon => {
        if (itemSon.parentId === item.id) {
          const childUrl = itemSon.resourceUrl.trim('/').split('/')
          childMenu.push(childUrl[childUrl.length - 1])
        }
      })
      item.childMenu = childMenu
    }
  })
  return menu
}

const filterRoutes = (menu, routes) => {
  const menuList = formatList(menu)
  const menuNameList = menu.map(item => item.resourceUrl)
  routes = routes.filter(item => menuNameList.includes(item.name))
  return routes.map(item => {
    const childRoute = item.children
    let childMenu
    menuList.map(value => {
      if (value.resourceUrl === item.name) childMenu = value
    })
    item.children = childRoute.filter(value => childMenu.childMenu.includes(value.name))
    return item
  })
}

export default {
  namespaced: true,
  state: {
    routes: [],
    menuRoutes: [],
    hasPermission: false,
    menuType: undefined, // 菜单类型：undefined: 订单管理 shop:能+营销
    hasMarketRight: false, // 是否有能+权限
    hasFund: false, // 是否有营销基金权限
  },
  getters: {},
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.routes = routes
    },
    SET_PERMISSION: (state, payload) => {
      state.hasPermission = payload.type
      state.menuRoutes = payload.needRoutes
    },
    CLEAR_PERMISSION: (state) => {
      state.hasPermission = false
      state.menuRoutes = []
      state.hasMarketRight = false
    },
    CHANGE_MENU: (state, payload) => {
      state.menuType = payload
    },
    SET_ORDER_MENU: (state, { type, hasMarketRight }) => {
      state.menuType = type
      state.hasMarketRight = hasMarketRight
    },
    SET_FUND: (state, { hasFund }) => {
      state.hasFund = hasFund
    }
  },
  actions: {
    generateRoutes ({commit}, routes) {
      commit('SET_ROUTES', routes)
    },
    async getNewRoute ({ state, commit }) {
      try {
        const {code, result} = await getMenuList()
        if (code !== 200) {
          // 防止路由守卫陷入死循环，返回[]
          commit('SET_PERMISSION', { needRoutes: [], type: false })
          return []
        }
        let needRoutes = filterRoutes(result, state.routes)
        const hasMarketRight = needRoutes.find(item => item.meta && item.meta.type === 'shop')
        const hasFund = needRoutes.find(item => item.path === '/fund')
        // if (hasMarketRight) {
        //   needRoutes.push({
        //     path: '/',
        //     redirect: '/home',
        //     hidden: true
        //   })
        //   if (!state.hasMarketRight) {
        //     commit('SET_ORDER_MENU', { type: 'shop', hasMarketRight: true })
        //   }  
        // } else {
        //   needRoutes.push({
        //     path: '/',
        //     redirect: '/order',
        //     hidden: true
        //   })
          // commit('SET_ORDER_MENU', { type: undefined, hasMarketRight: false })
        // }
        commit('SET_ORDER_MENU', { type: undefined, hasMarketRight })
        if (hasFund) commit('SET_FUND', { hasFund: true })
        commit('SET_PERMISSION', {needRoutes, type: true})
        return needRoutes
      } catch (err) {
        console.log(err)
      }
    },
    resetPermission ({commit}) {
      resetRouter()
      commit('CLEAR_PERMISSION')
    },
    changeMenu ({commit}, menuType) {
      commit('CHANGE_MENU', menuType)
    }
  }
}